from django import forms
from django.contrib.auth import get_user_model
from blog_auth.models import verify_email


class RegisterForm(forms.Form):
    verify_email = verify_email
    User = get_user_model()
    username = forms.CharField(min_length=2, max_length=20,
                               error_messages={'required': "请输入用户名", 'min_length': "用户名长度不能小于2位",
                                               'max_length': "用户名长度不能大于20位"})

    email = forms.EmailField(error_messages={'required': "请输入邮箱地址", 'invalid': "邮箱格式错误"})

    code = forms.CharField(min_length=4, max_length=4,
                           error_messages={'required': "请输入验证码", 'min_length': "验证码长度不能小于4位",
                                           'max_length': "验证码长度不能大于4位"})
    password = forms.CharField(min_length=6, max_length=256,
                               error_messages={'required': "请输入密码", 'min_length': "密码长度不能小于6位",
                                               'max_length': "密码长度不能大于256位"})

    def clean_code(self):
        code = self.cleaned_data.get('code')
        email = self.cleaned_data.get('email')
        verify_email1 = self.verify_email.objects.filter(email=email).first()
        if verify_email1 and verify_email1.code == code:
            return code
        else:
            raise forms.ValidationError('验证码错误')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if self.User.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已存在')
        return email
